package com.sleepcamel.resteasyConfigurator.components.tree;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;

import com.sleepcamel.rest.domain.Project;
import com.sleepcamel.rest.domain.ProjectRootItem;
import com.sleepcamel.rest.domain.TreeNode;
import com.sleepcamel.resteasyConfigurator.components.tree.strategies.PackageTreeContentStrategy;

public class ProjectTreeContentProvider implements ITreeContentProvider, PropertyChangeListener {

	protected TreeViewer treeViewer;
	private ITreeContentStrategy contentStrategy = new PackageTreeContentStrategy();
	
	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		treeViewer = (TreeViewer)viewer;
		ProjectRootItem oldProject = (ProjectRootItem) oldInput;
		ProjectRootItem newProject = (ProjectRootItem) newInput;
		if(oldProject != null) {
			removeListeners(oldProject);
		}
		if(newProject != null) {
			addListeners(newProject);
		}
	}
	
	private void addListeners(ProjectRootItem newRoot) {
		List<Project> projects = newRoot.getChilds();
		projects.get(0).addPropertyChangeListener(this);
	}

	private void removeListeners(ProjectRootItem oldRoot) {
		List<Project> projects = oldRoot.getChilds();
		projects.get(0).removePropertyChangeListener(this);
	}
	
	public ITreeContentStrategy getContentStrategy() {
		return contentStrategy;
	}

	public void setContentStrategy(ITreeContentStrategy contentStrategy) {
		this.contentStrategy = contentStrategy;
	}

	@Override
	public Object[] getChildren(Object arg0) {
		return contentStrategy.getChildren(arg0);
	}

	@Override
	public Object getParent(Object arg0) {
		return contentStrategy.getParent(arg0);
	}

	@Override
	public Object[] getElements(Object arg0) {
		if ( arg0 instanceof ProjectRootItem){
			return new Object[]{((ProjectRootItem) arg0).getChilds().get(0)};
		}
		return null;
	}


	@Override
	public boolean hasChildren(Object arg0) {
		return getChildren(arg0).length > 0;
	}

	@Override
	public void propertyChange(PropertyChangeEvent propertyChangedEvent) {
		Object entity = (Object) propertyChangedEvent.getSource();
		String propertyName = propertyChangedEvent.getPropertyName();
		if ( propertyName.equals("child") ){
			TreeNode newValue = (TreeNode) propertyChangedEvent.getNewValue();
			if ( newValue != null )
				newValue.addPropertyChangeListener(this);
		}
		treeViewer.update(entity, new String[]{propertyName});
		treeViewer.refresh(true);
	}

}
